<template>
  <el-container class="GoodSkuList">
    <el-header class="mt20">
      <div class="flex" style="justify-content: space-between;">
        <span class="title fs18 mr10">规格列表</span>
        <el-input v-model="listQuery.value" size="medium" clearable style="width: 500px;max-width: 100%;" @change="getList" @clear="getList">
          <el-button slot="append" icon="el-icon-search" @click="getList">搜索</el-button>
        </el-input>
      </div>
      <el-divider />
    </el-header>
    <el-main v-loading="loading">
      <el-row class="GoodSkuList-title" style="padding: 15px 0px 15px 30px;text-align: center;font-size: 16px;">
        <el-col :span="3">上架时间</el-col>
        <el-col :span="3">商品封面</el-col>
        <el-col :span="3">商品名称</el-col>
        <el-col :span="3">商品标签</el-col>
        <el-col :span="2">商品类别</el-col>
        <el-col :span="3">商品库存</el-col>
        <el-col :span="2">是否无规格商品</el-col>
        <el-col :span="5">操作</el-col>
      </el-row>
      <el-collapse v-model="activeNames" class="GoodSkuList-collapse">
        <el-collapse-item v-for="(item, index) in tableData" :key="index" :name="item.id">
          <!-- 商品信息 -->
          <el-row slot="title" :gutter="20" class="flex fs15" style="width: 100%;height: 100%;text-align: center;margin: 0;">
            <el-col :span="3">{{ item.createTime | setTime }}</el-col>
            <el-col :span="3"><Cimage :src="item.iconId[0].url" fit="cover" style="cursor: pointer;border-radius: 5px;" width="50px" height="50px" @click.stop.native="openViewr(item.iconId[0].url)" /></el-col>
            <el-col :span="3" class="twoLineEllipsis">{{ item.name | isNullData }}</el-col>
            <el-col :span="3">{{ item.hot | isNullData }}</el-col>
            <el-col :span="2">{{ item.typeName | isNullData }}</el-col>
            <el-col :span="3">{{ item.stock_num | isNullData }}</el-col>
            <el-col :span="2">{{ item.none_sku ? '是' : '否' }}</el-col>
            <el-col :span="5">
              <el-button type="info" icon="el-icon-search" size="small" @click="toDetailsGoods(item.id)">查看</el-button>
              <el-button size="small" icon="el-icon-plus" type="primary" @click.stop="openDialog(item, 'add')">添加列表</el-button>
            </el-col>
          </el-row>
          <!-- 该商品下的规格列表 -->
          <el-row v-for="(it, idx) in item.list" :key="it.id" :gutter="20" class="fs15 mb15" style="width: 100%;height: 100%;">
            <el-col :span="3"><span>{{ idx + 1 }}、 </span> {{ it.createTime | setTimeMini }}</el-col>
            <el-col :span="11" class="flex">
              <span v-for="i in it.data" :key="i.id" style="flex: 1;padding-right: 10px;">
                {{ i.k | isNullData }} - {{ i.name | isNullData }}
              </span>
            </el-col>
            <el-col :span="2">￥{{ it.price }}</el-col>
            <el-col :span="3">剩余库存：{{ it.stock_num|isNullData }}</el-col>
            <el-col :span="5" style="text-align: center;">
              <el-button size="small" icon="el-icon-edit" type="primary" class="mr10" @click="openDialog(item, 'modify', it)">修 改</el-button>
              <el-popconfirm
                title="确定要执行该操作吗？"
                @confirm="removeSkuItem(it)"
              >
                <el-button slot="reference" size="small" icon="el-icon-delete" type="danger">删 除</el-button>
              </el-popconfirm>
            </el-col>
          </el-row>
          <el-row v-if="item.list.length === 0"><el-col :span="24" class="fs15" style="text-align: center;">该商品未添加规格列表</el-col></el-row>
        </el-collapse-item>
      </el-collapse>
      <Cpagination
        :total="listQuery.total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.size"
        @pagination="getList"
      />
    </el-main>
    <CImageViewer :viewer-image-url.sync="viewr.viewerImageUrl" :visible.sync="viewr.visible" />
    <Cdialog
      :visible="dialog.visible"
      :title="dialog.title"
      width="700px"
      class="GoodSkuList-dialog"
      @handleClose="handleClose"
    >
      <div class="GoodSkuList-dialog-content">
        <div v-for="item in dialog.item.skuList" :key="item.id" class="mb15 flex">
          <span class="mr15 mb5">{{ item.k | isNullData }}</span>
          <!-- 组件会自动新增vId这个字段 -->
          <el-radio-group v-if="item.v.length > 0" v-model="item.vId" size="medium" class="GoodSkuList-dialog-content-group" @change="() => { addSkuChange(item) }">
            <el-radio-button v-for="it in item.v" :key="it.id" :label="it.id" :class="it.previewImgUrl ? 'previewImgUrlButton' : ''">
              <Cimage v-if="it.previewImgUrl" :src="it.previewImgUrl[0].url" width="36px" height="36px" fit="cover" class="mr10" />
              <span>{{ it.name | isNullData }}</span>
            </el-radio-button>
          </el-radio-group>
          <el-tag v-else type="danger">未有数据，请添加规格值</el-tag>
        </div>
        <Cinput v-model="dialog.stock_num" type="number" placeholder="库存" style="width: 100%;" class="mt30">输入该选项库存</Cinput>
        <Cinput v-model="dialog.price" type="number" placeholder="价格" style="width: 100%;" class="mt30">输入该选项价格</Cinput>
      </div>
      <div slot="footer" class="flexCenter">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="small" @click="submitAddSku">提 交</el-button>
      </div>
    </Cdialog>
  </el-container>
</template>
<script>
import {
  categoryGetTwo
} from '@/api/category'
import {
  myGoodsDetail,
  myGoodsList
} from '@/api/myGoods'
import {
  goodsSkuListModifyList,
  goodsSkuListDeleteList
} from '@/api/goodsSkuList'
export default {
  name: 'GoodSkuList',
  data() {
    return {
      activeNames: [],
      tableData: [], // 主数据
      loading: true,
      listQuery: {
        total: 0,
        page: 1,
        size: 10,
        value: '' // 模糊搜索字段
      },
      viewr: { // 图片预览数据
        visible: false,
        viewerImageUrl: []
      },
      dialog: {
        visible: false,
        title: '',
        item: '', // 单个商品数据

        id: '', // 单个规格列表的id
        stock_num: '', // 剩余库存
        price: '', // 单个规格列表价格
        skuValue: {} // 选择的sku
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 删除单个规格列表
    async removeSkuItem(it) {
      const res = await goodsSkuListDeleteList({ ids: it.id })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getList()
      }
    },
    // 提交保存（新增规格列表）
    async submitAddSku() {
      // 如果对话框的sku对象值长度不够这个商品的规格列表长度（说明没有选完）
      if (Object.keys(this.dialog.skuValue).length !== this.dialog.item.skuList.length) {
        this.$message.error('请选择规格')
        return
      }
      if (!this.dialog.stock_num) {
        this.$message.error('请输入库存')
        return
      }
      if (!this.dialog.price) {
        this.$message.error('请输入价格')
        return
      }
      const res = await goodsSkuListModifyList({
        id: this.dialog.id || undefined,
        parentId: this.dialog.item.id,
        price: this.dialog.price,
        stock_num: this.dialog.stock_num,
        ...this.dialog.skuValue // 选择的sku
      })
      if (res.code === 0) {
        this.$message.success(this.dialog.id ? '修改成功' : '添加成功')
        this.handleClose()
        this.getList()
      }
    },
    // 选择规格（新增规格列表）
    addSkuChange(item) {
      this.dialog.skuValue[item.k_s] = item.vId // 直接用对象方式（可以替换也可以增加）
      this.$forceUpdate()
    },
    // 关闭对话框
    handleClose() {
      this.dialog = {
        visible: false,
        title: '',
        item: '', // 单个商品数据
        stock_num: '', // 剩余库存
        price: '', // 单个规格列表价格
        skuValue: {} // 选择的sku
      }
    },
    // 打开对话框
    openDialog(goodsItem, type, goosSkuItem) {
      if (goodsItem.skuList.length === 0 || goodsItem.none_sku) {
        this.$message.error('该商品未有可选Sku，不能增加规格列表')
        return
      }
      switch (type) {
        case 'add':
          this.dialog.title = '添加规格列表'
          break
        case 'modify':
          goodsItem.skuList.forEach(item => {
            for (const key in goosSkuItem) {
              for (const prop in item) {
                if (key === item[prop]) {
                  item['vId'] = goosSkuItem[key] // 初始化默认选中值
                  this.dialog.skuValue[key] = goosSkuItem[key] // 初始化接口需要的数据
                }
              }
            }
          })
          this.dialog.id = goosSkuItem.id
          this.dialog.price = goosSkuItem.price
          this.dialog.stock_num = goosSkuItem.stock_num
          this.dialog.title = '编辑规格列表'
          console.log(this.dialog)
          break
      }
      this.dialog.item = goodsItem
      this.dialog.visible = true
    },
    // 打开预览大图组件
    openViewr(url) {
      console.log('触发')
      this.viewr.viewerImageUrl = [url]
      this.viewr.visible = true
    },
    // 跳转商品详情
    toDetailsGoods(id) {
      this.$router.push({
        name: 'GoodsDetails',
        path: '/goods/details',
        query: { id: id }
      })
    },
    // 初始化数据
    async getList() {
      this.loading = true
      const good_res = await myGoodsList(this.listQuery) // 查询商品
      if (good_res.code === 0) {
        const { data: goodData } = good_res
        const value = await this.filterCategory(goodData.list)
        let flag = 0
        for (let i = 0; i < value.length; i++) {
          myGoodsDetail({ goodsId: value[i].id }).then(goodsDetail_res => {
            if (goodsDetail_res.code === 0) {
              const { data: goodsDetail_data } = goodsDetail_res
              if (goodsDetail_data.list && goodsDetail_data.list.length > 0) { // 格式化规格列表（匹配值）
                goodsDetail_data.list.forEach(item => {
                  item['data'] = []
                  goodsDetail_data.skuList.forEach(value => {
                    item['data'] = this.formatSku(item, value)
                  })
                })
              }
              value[i] = { typeName: value[i].typeName, ...goodsDetail_data }
              flag++
              if (flag === value.length) { // 收集数据完成
                this.tableData = value
                this.loading = false
                this.listQuery.total = goodData.total
                this.activeNames = this.tableData[0].id // 手风琴默认显示第一行
                console.log(this.tableData, '商品规格列表数据')
              }
            }
          })
          // this.goodsDetails(value[i].id).then(goodsDetails => {
          //   value[i] = { typeName: value[i].typeName, ...goodsDetails }
          //   flag++
          //   if (flag === value.length) { // 收集数据完成
          //     this.tableData = value
          //     this.loading = false
          //     this.listQuery.total = goodData.total
          //     console.log(this.tableData, '商品规格列表数据')
          //   }
          // })
        }
      }
    },
    // 格式化规格列表（匹配值）
    formatSku(item, skuItem) {
      for (const prop in item) {
        for (const key in skuItem) {
          // eslint-disable-next-line eqeqeq
          if (prop == skuItem[key]) {
            const index = skuItem.v.findIndex(it => it.id === item[prop]) // 获取索引
            item['data'].push({
              k: skuItem.k,
              key: prop,
              id: item[prop],
              name: skuItem.v[index].name
            })
          }
        }
      }
      return item['data']
    },
    // 商品分类匹配
    filterCategory(list) {
      return new Promise(resolve => {
        if (list.length === 0) {
          resolve(list)
          return
        }
        categoryGetTwo().then(res => { // 直接获取全部二级分类
          if (res.code === 0) {
            const { data } = res
            list.forEach(item => {
              const index = data.findIndex(v => item.parentId === v.id)
              item['typeName'] = data[index].name || '未命名分类'
            })
            resolve(list)
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/element-variables.scss";
.GoodSkuList{
  &-title{
    background-color: rgba($color: $--color-primary, $alpha: .09);
  }
  &-collapse{
    border-top: 0;
    border-bottom: 0;
    ::v-deep .el-collapse-item{
      margin: 20px 0;
      &__header{
        flex-direction: row-reverse;
        height: inherit;
        line-height: inherit;
        padding: 10px 0;
        border-bottom: 0;
        // background-color: #e9f2ff;
        background-color: rgba($color: $--color-primary, $alpha: .09);
      }
      &__arrow{
        font-size: 16px;
        font-weight: bold;
        margin: 0;
        margin-left: 15px;
      }
      &__wrap{
        border-bottom: 0;
      }
      &__content{
        background-color: rgba($color: $--color-primary, $alpha: .05);
        padding: 10px 0 10px 40px;
      }
    }
  }
  &-dialog{
    &-content{
      width: 100%;
      height: 100%;
      padding: 10px 20px;
      &-group{
      ::v-deep .el-radio-button__inner{
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 14px;
        height: 36px;
        margin-bottom: 5px;
      }
    }
    }
  }
}
.previewImgUrlButton{
  ::v-deep .el-radio-button__inner{
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    padding-right: 14px;
    height: 36px;
    margin-bottom: 5px;
  }
}
</style>
